class BrainManager {
    constructor() {
        this.chart = null;
        this.keywords = [];
        this.relations = [];
        this.documentCount = 0;
        this.uploadStatus = document.querySelector('.upload-status');
        this.progressBar = document.querySelector('.progress-inner');
        this.progressText = document.querySelector('.progress-text');
        
        this.initializeChart();
        this.initializeFileUpload();
        this.loadBrainData();
    }

    initializeChart() {
        const chartDom = document.getElementById('brainChart');
        this.chart = echarts.init(chartDom);
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.chart.resize();
        });
    }

    initializeFileUpload() {
        const fileInput = document.getElementById('docUpload');
        fileInput.addEventListener('change', (e) => this.handleFileUpload(e));
    }

    async handleFileUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        // 显示上传状态
        this.uploadStatus.style.display = 'block';
        this.progressBar.style.width = '0%';
        this.progressText.textContent = '正在处理文档...';

        try {
            // 读取文件内容
            const content = await this.readFileContent(file);
            
            // 更新进度
            this.progressBar.style.width = '30%';
            this.progressText.textContent = '正在提取关键词...';

            // 提取关键词
            const keywords = await this.extractKeywords(content);
            
            // 更新进度
            this.progressBar.style.width = '60%';
            this.progressText.textContent = '正在分析关联关系...';

            // 分析关联关系
            const relations = await this.analyzeRelations(keywords);
            
            // 更新进度
            this.progressBar.style.width = '90%';
            this.progressText.textContent = '正在更新图谱...';

            // 更新数据和图表
            this.updateBrainData(keywords, relations);
            
            // 完成
            this.progressBar.style.width = '100%';
            this.progressText.textContent = '处理完成';
            
            // 3秒后隐藏进度条
            setTimeout(() => {
                this.uploadStatus.style.display = 'none';
                this.progressBar.style.width = '0%';
            }, 3000);

        } catch (error) {
            console.error('处理文档失败:', error);
            this.progressText.textContent = '处理失败，请重试';
            
            setTimeout(() => {
                this.uploadStatus.style.display = 'none';
                this.progressBar.style.width = '0%';
            }, 3000);
        }

        // 清除文件选择
        event.target.value = '';
    }

    readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            
            reader.onload = async (e) => {
                try {
                    let content = e.target.result;
                    
                    // 检测编码
                    if (this.isUTF8(content)) {
                        resolve(content);
                    } else {
                        // 如果不是UTF-8，尝试用GBK重新读取
                        const gbkReader = new FileReader();
                        gbkReader.onload = (e) => {
                            try {
                                // 使用 TextDecoder 解码 GBK
                                const decoder = new TextDecoder('gbk');
                                content = decoder.decode(e.target.result);
                                resolve(content);
                            } catch (error) {
                                reject(new Error('不支持的文件编码'));
                            }
                        };
                        gbkReader.onerror = () => reject(new Error('文件读取失败'));
                        gbkReader.readAsArrayBuffer(file);
                    }
                } catch (error) {
                    reject(error);
                }
            };
            
            reader.onerror = (e) => reject(e);
            
            if (file.type === 'application/pdf') {
                reject(new Error('PDF文件支持即将推出'));
            } else {
                reader.readAsText(file, 'UTF-8');
            }
        });
    }

    isUTF8(str) {
        try {
            const encoder = new TextEncoder();
            const decoder = new TextDecoder('utf-8');
            const bytes = encoder.encode(str);
            const decoded = decoder.decode(bytes);
            return decoded === str;
        } catch (e) {
            return false;
        }
    }

    async extractKeywords(content) {
        // 首先移除所有HTML标签和特殊字符
        content = content.replace(/<[^>]+>/g, '')
                        .replace(/\[TOC\]/gi, '')
                        .replace(/^\s*[\d.]+\s*/gm, '')
                        .replace(/\{[^}]+\}/g, '')
                        .replace(/\[[^\]]+\]/g, '')
                        .replace(/[^\u4e00-\u9fa5。！？]/g, ''); // 只保留中文和句号

        // 分割成句子
        const sentences = content.split(/[。！？]/);
        
        // 提取2-4个字的中文词组
        const wordCount = {};
        const wordPattern = /[\u4e00-\u9fa5]{2,4}/g;
        
        sentences.forEach(sentence => {
            const matches = sentence.match(wordPattern);
            if (matches) {
                matches.forEach(word => {
                    if (!this.isStopWord(word)) {
                        wordCount[word] = (wordCount[word] || 0) + 1;
                    }
                });
            }
        });

        // 转换为数组并按出现频率排序
        const sortedWords = Object.entries(wordCount)
            .sort((a, b) => b[1] - a[1])
            .filter(([word, count]) => count >= 3); // 至少出现3次

        // 只取前5个最高频的关键词
        return sortedWords.slice(0, 5).map(([text, weight]) => ({
            text,
            weight
        }));
    }

    isStopWord(word) {
        // 扩展停用词列表
        const stopWords = new Set([
            '的', '了', '和', '是', '就', '都', '而', '及', '与', '这',
            '那', '但是', '所以', '因为', '如果', '什么', '这个', '那个',
            '可以', '没有', '我们', '你们', '他们', '它们', '时候', '这样',
            '那样', '如此', '这些', '那些', '一个', '一些', '一样', '现在',
            '已经', '还是', '只是', '可能', '不会', '这种', '那种', '进行',
            '表示', '指出', '认为', '觉得', '知道', '需要', '希望', '要求',
            '自己', '一直', '一定', '一样', '一般', '一起', '一些', '主要',
            '不同', '不要', '不过', '不能', '不是', '之前', '之后', '之间',
            '任何', '具有', '出现', '包括', '方面', '没有', '特别', '甚至',
            '直接', '相关', '知道', '确实', '问题', '其他', '发现', '比较'
        ]);
        return stopWords.has(word);
    }

    async analyzeRelations(keywords) {
        const relations = [];
        
        // 对于5个关键词，两两建立连接
        for (let i = 0; i < keywords.length; i++) {
            for (let j = i + 1; j < keywords.length; j++) {
                // 根据两个关键词的权重计算连接强度
                const strength = Math.min(5, Math.floor((keywords[i].weight + keywords[j].weight) / 4));
                
                relations.push({
                    source: keywords[i].text,
                    target: keywords[j].text,
                    strength: strength
                });
            }
        }

        return relations;
    }

    updateBrainData(newKeywords, newRelations) {
        // 合并现有数据和新数据，避免重复
        const keywordMap = new Map(this.keywords.map(k => [k.text, k]));
        newKeywords.forEach(keyword => {
            if (keywordMap.has(keyword.text)) {
                // 如果关键词已存在，增加权重
                keywordMap.get(keyword.text).weight += keyword.weight;
            } else {
                keywordMap.set(keyword.text, keyword);
            }
        });
        
        // 转换回数组
        this.keywords = Array.from(keywordMap.values());
        
        // 更新关联关系，避免重复
        const relationSet = new Set(this.relations.map(r => `${r.source}-${r.target}`));
        const newUniqueRelations = newRelations.filter(relation => 
            !relationSet.has(`${relation.source}-${relation.target}`) &&
            !relationSet.has(`${relation.target}-${relation.source}`)
        );
        
        this.relations = [...this.relations, ...newUniqueRelations];
        
        // 更新文档计数
        this.documentCount++;
        
        // 更新统计数据
        this.updateStats();
        
        // 重新渲染图表
        this.renderChart();
    }

    updateStats() {
        const stats = document.querySelectorAll('.brain-stats .stat-value');
        stats[0].textContent = this.keywords.length;
        stats[1].textContent = this.relations.length;
        stats[2].textContent = this.documentCount;
    }

    renderChart() {
        const option = {
            title: {
                text: '思维云图',
                subtext: '基于您的生活记录生成',
                top: 'top',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: 出现{c}次'
            },
            legend: {
                show: false
            },
            animationDurationUpdate: 1500,
            animationEasingUpdate: 'quinticInOut',
            series: [{
                type: 'graph',
                layout: 'force',
                force: {
                    repulsion: 200,  // 增加斥力
                    gravity: 0.05,   // 减小引力
                    edgeLength: 150, // 增加边长
                    layoutAnimation: true
                },
                roam: true,
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{b}',
                    fontSize: 14
                },
                data: this.keywords.map(keyword => ({
                    name: keyword.text,
                    value: keyword.weight,
                    symbolSize: Math.sqrt(keyword.weight) * 12, // 增大节点大小
                    draggable: true,
                    itemStyle: {
                        color: this.getRandomColor()
                    }
                })),
                links: this.relations.map(relation => ({
                    source: relation.source,
                    target: relation.target,
                    value: relation.strength,
                    lineStyle: {
                        width: Math.sqrt(relation.strength) * 2,
                        curveness: 0.3,
                        opacity: 0.7
                    }
                })),
                emphasis: {
                    focus: 'adjacency',
                    lineStyle: {
                        width: 10
                    }
                }
            }]
        };

        this.chart.setOption(option);
    }

    getRandomColor() {
        const colors = [
            '#4169E1', // 主色调
            '#67E0E3', // 次要色调
            '#32C5E9',
            '#37A2DA',
            '#9FE6B8',
            '#FFDB5C',
            '#FF9F7F',
            '#FB7293',
            '#E062AE',
            '#E690D1'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    // API 调用方法
    async fetchBrainData() {
        // TODO: 实现从服务器获取云脑数据的逻辑
        return {
            keywords: [
                { text: '工作', weight: 100 },
                { text: '生活', weight: 80 },
                { text: '家庭', weight: 90 },
                { text: '健康', weight: 85 },
                { text: '学习', weight: 75 },
                { text: '旅行', weight: 60 },
                { text: '美食', weight: 50 },
                { text: '运动', weight: 70 },
                { text: '阅读', weight: 65 },
                { text: '音乐', weight: 55 }
            ],
            relations: [
                { source: '工作', target: '学习', strength: 5 },
                { source: '生活', target: '健康', strength: 4 },
                { source: '家庭', target: '生活', strength: 6 },
                { source: '健康', target: '运动', strength: 5 },
                { source: '学习', target: '阅读', strength: 4 },
                { source: '旅行', target: '生活', strength: 3 },
                { source: '美食', target: '生活', strength: 3 },
                { source: '运动', target: '生活', strength: 4 },
                { source: '音乐', target: '生活', strength: 3 }
            ]
        };
    }
}

// 创建云脑管理器实例
window.brainManager = new BrainManager(); 